package org.chiv.nxone.network.httpcomponent.server;

import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.NetServerOptions;
import lombok.extern.slf4j.Slf4j;
import org.chiv.nxone.network.base.ServerProvider;
import org.chiv.nxone.network.base.exception.ServerException;

@Slf4j
public class HttpServerProvider implements ServerProvider {

    private Vertx vertx;
    VertxHttpServer vertxHttpServer;

    /**
     * 创建服务
     */
    @Override
    public void createServer(NetServerOptions netServerOptions) {
        if (netServerOptions == null) {
            throw new ServerException("网络配置为null,无法启动网络");
        }
        vertxHttpServer = new VertxHttpServer();
        vertxHttpServer.setHttpGateway(new HttpGateway());
        //根据核心数量创建
        HttpServer httpServer = vertx.createHttpServer((HttpServerOptions) netServerOptions);
        httpServer.requestHandler(this::receiveRequest);
        httpServer.listen(this::listen);


    }

    /**
     * 接受http 请求
     *
     * @param httpServerRequest
     */
    public void receiveRequest(HttpServerRequest httpServerRequest) {
        String queryParams = httpServerRequest.query();

        httpServerRequest.bodyHandler(body -> {
            String data = body.toString();
            vertxHttpServer.sent(data);
        });


        httpServerRequest.response().end("ok");


    }

    /**
     * 重置服务
     */
    @Override
    public void reload() {

    }

    @Override
    public boolean isAlive() {
        return true;
    }

    public static void main(String[] args) {
        HttpServerProvider provider = new HttpServerProvider();
        provider.vertx = Vertx.vertx(new VertxOptions().setWorkerPoolSize(10));
        provider.createServer(new HttpServerOptions().setPort(8001));
    }
}
